package com.example.demo.utils;

import lombok.Data;
import lombok.experimental.Accessors;

/**
 * 统一API响应结果封装
 */
@Data
@Accessors(chain = true) // 启用链式调用
public class Response<T> {
    private int code;    // 状态码
    private String msg;  // 消息
    private T data;      // 返回数据

    // 常用状态码常量
    public static final int SUCCESS = 200;
    public static final int BAD_REQUEST = 400;
    public static final int UNAUTHORIZED = 401;
    public static final int FORBIDDEN = 403;
    public static final int NOT_FOUND = 404;
    public static final int INTERNAL_SERVER_ERROR = 500;

    /**
     * 成功响应（无数据）
     */
    public static <T> Response<T> success() {
        return new Response<T>()
                .setCode(SUCCESS)
                .setMsg("操作成功");
    }

    /**
     * 成功响应（带数据）
     */
    public static <T> Response<T> success(T data) {
        return new Response<T>()
                .setCode(SUCCESS)
                .setMsg("操作成功")
                .setData(data);
    }

    /**
     * 失败响应
     */
    public static <T> Response<T> fail(int code, String msg) {
        return new Response<T>()
                .setCode(code)
                .setMsg(msg);
    }

    /**
     * 失败响应（带数据）
     */
    public static <T> Response<T> fail(int code, String msg, T data) {
        return new Response<T>()
                .setCode(code)
                .setMsg(msg)
                .setData(data);
    }

    // 常用快捷方法
    public static <T> Response<T> badRequest(String msg) {
        return fail(BAD_REQUEST, msg);
    }

    public static <T> Response<T> unauthorized(String msg) {
        return fail(UNAUTHORIZED, msg);
    }

    public static <T> Response<T> forbidden(String msg) {
        return fail(FORBIDDEN, msg);
    }

    public static <T> Response<T> notFound(String msg) {
        return fail(NOT_FOUND, msg);
    }

    public static <T> Response<T> serverError(String msg) {
        return fail(INTERNAL_SERVER_ERROR, msg);
    }

    /**
     * 判断是否成功
     */
    public boolean isSuccess() {
        return code == SUCCESS;
    }

}
